package wangm.config;


import wangm.util.PropertiesUtils;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.sql.DataSource;

import java.io.File;

import static wangm.constant.Constant.PROPERTIES.*;
import static wangm.constant.Constant.SYSTEM.INIT_SQL_FILENAME;


/**
 * db 初始化
 *
 * @author zk
 * @date 2018-02-23 15:53
 */
@Component
public class DbInitializer implements WebApplicationInitializer {
    private static Logger logger = LoggerFactory.getLogger(DbInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        String initDb = PropertiesUtils.getString(DB_INIT);
        if(!StringUtils.isEmpty(initDb) && Boolean.valueOf(initDb)){
            try {
                Long beginTime = System.currentTimeMillis();
                initializerDB();
                Long endTime = System.currentTimeMillis();
                logger.info("init h2 db success ,total cast {}ms",endTime - beginTime);

            } catch (Exception e) {
                logger.error("init db fail : ",e.getMessage());
            }
        }
    }

    /**
     * 初始化DB.sql
     */
    public void initializerDB() throws Exception {
        try {
            String db_driver = PropertiesUtils.getString(DB_DRIVER);
            String db_url = PropertiesUtils.getString(DB_URL);
            String db_username = PropertiesUtils.getString(DB_USERNAME);
            String db_password = PropertiesUtils.getString(DB_PASSWORD);

            String initSqlFilePath = Thread.currentThread().getContextClassLoader().getResource(INIT_SQL_FILENAME).getPath();
            SQLExec sqlExec = new SQLExec();
            sqlExec.setSrc(new File(initSqlFilePath));
            sqlExec.setDriver(db_driver);
            sqlExec.setUrl(db_url);
            sqlExec.setUserid(db_username);
            sqlExec.setPassword(db_password);

            sqlExec.setPrint(true);
            sqlExec.setProject(new Project());
            sqlExec.execute();
        } catch (BuildException e) {
            throw new Exception(e.getMessage());
        }
    }
}
